const Like = require('../models/like');
const Notification = require('../models/notification');
const Post = require('../models/post');

const likeController = {
    async likePost(req, res, next) {
        try {
            const post = await Post.findById(req.params.post_id);
            if (!post) {
                return res.status(404).json({ error: 'Post not found' });
            }

            const exists = await Like.exists(req.user.user_id, req.params.post_id);
            if (exists) {
                return res.status(400).json({ error: 'Already liked' });
            }

            await Like.create({ user_id: req.user.user_id, post_id: req.params.post_id });

            if (post.user_id !== req.user.user_id) {
                await Notification.create({
                    user_id: post.user_id,
                    type: 'like',
                    related_user_id: req.user.user_id,
                    related_post_id: req.params.post_id,
                    content: `${req.user.user_id} liked your post`
                });
            }

            res.json({ message: 'Post liked' });
        } catch (error) {
            next(error);
        }
    },

    async unlikePost(req, res, next) {
        try {
            const exists = await Like.exists(req.user.user_id, req.params.post_id);
            if (!exists) {
                return res.status(400).json({ error: 'Not liked' });
            }

            await Like.delete(req.user.user_id, req.params.post_id);
            res.json({ message: 'Post unliked' });
        } catch (error) {
            next(error);
        }
    }
};

module.exports = likeController;